<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button type="primary" :disabled="isaddress" @click="add()">添加员工</a-button>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <el-form :inline="true" size="mini">
          <el-form-item label="员工姓名">
            <el-input v-model="mname" placeholder="员工姓名"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="mphone" placeholder="手机号"></el-input>
          </el-form-item>
          <el-form-item label="校区">
            <el-select v-model="search" placeholder="校区">
              <el-option label="全部校区" value></el-option>
              <el-option
                v-for="(item, i) in getschooladdress"
                :key="`2inline${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-table
          :data="tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
          style="width: 100%; border: 1px solid #eeeeee"
        >
          <el-table-column label="序号" width="60">
            <template slot-scope="scope">{{scope.$index+1}}</template>>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="110">
            <template slot-scope="scope">
              <el-button
                type="text"
                v-text="scope.row.name"
                @click="watchthis = true ; index = scope.row.ID"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column sortable prop="sex" label="性别" width="80"></el-table-column>
          <el-table-column prop="phonenum" label="手机号"></el-table-column>
          <el-table-column sortable prop="detailedaddress" label="校区">
            <template
              slot-scope="scope"
            >{{scope.row.schooladdressid? getschooladdress.find(v=> v.ID == scope.row.schooladdressid).name:'全部校区'}}</template>
          </el-table-column>
          <el-table-column sortable prop="detailedaddress" label="角色">
            <template
              slot-scope="scope"
            >{{ scope.row.schoolroleid? getschoolrole.find(v=> v.ID == scope.row.schoolroleid).name:''}}</template>
          </el-table-column>
          <el-table-column sortable prop="isteacher" label="是否授课" width="120">
            <template slot-scope="scope">{{scope.row.isteacher?'是':'否'}}</template>
          </el-table-column>
          <el-table-column align="left" width="230px">
            <template slot-scope="scope">
              <el-button
                type="primary"
                v-if="scope.row.type !=='root'"
                size="mini"
                @click="add(scope.row)"
              >编辑</el-button>
              <el-button
                v-if="scope.row.type !=='root'"
                size="mini"
                type="danger"
                @click="del(scope.row.ID)"
              >删除</el-button>
              <el-button
                v-if="scope.row.type !=='root'"
                size="mini"
                :type="scope.row.state?'info':'warning'"
                @click="state(scope.row)"
              >{{ scope.row.state?'启用':'停用' }}</el-button>
              <span v-if="scope.row.type ==='root'">这是创建者无法修改</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          @current-change="currentChange"
          :page-size="pagesize"
          layout="total, prev, pager, next"
          :total="tableData.length"
        ></el-pagination>
        <el-dialog class="school-form" :title="title" width="510px" :visible.sync="setaddress">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini">
            <el-form-item v-if="title !== '修改员工' " label="员工名称" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item v-if="title !== '修改员工' " label="性别" prop="sex">
              <el-radio-group v-model="ruleForm.sex">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="title !== '修改员工' " label="手机号码" prop="phonenum">
              <el-input v-model="ruleForm.phonenum"></el-input>
            </el-form-item>
            <el-form-item label="员工密码" prop="password">
              <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item label="选择校区">
              <el-select v-model="ruleForm.schooladdressid" allow-create placeholder="请选择校区">
                <el-option label="全部校区" :value="0"></el-option>
                <el-option
                  v-for="(item, i) in getschooladdress"
                  :key="`4user${i}`"
                  :label="item.name"
                  :value="item.ID"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="schoolroleid">
              <el-select v-model="ruleForm.schoolroleid" allow-create placeholder="请选择角色">
                <el-option
                  v-for="(item, i) in getschoolrole"
                  :key="`3user${i}`"
                  :label="item.name"
                  :value="item.ID"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否是教师">
              <el-radio-group v-model="ruleForm.isteacher">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="上课范围" v-show="ruleForm.isteacher" prop="classscope">
              <el-radio-group v-model="resource">
                <el-radio :label="true">全部校区</el-radio>
                <el-radio :label="false">指定校区</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-checkbox-group class="checkbox-group" v-show="!resource && ruleForm.isteacher" v-model="checkList">
              <el-checkbox
                v-for="(v, i) in getschooladdress"
                :key="`2user${i}`"
                :label="v.ID"
              >{{v.name}}</el-checkbox>
            </el-checkbox-group>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
            <el-button @click="setaddress = false" size="mini">取 消</el-button>
          </div>
        </el-dialog>
        <el-dialog class="school-form" title="个人详情" width="510px" :visible.sync="watchthis">
          <el-form class="htedialogtext" v-if="watchthis" label-width="150px" size="mini">
            <el-form-item label="姓名">
              <span v-text="scope.name"></span>
            </el-form-item>
            <el-form-item label="性别">
              <span v-text="scope.sex"></span>
            </el-form-item>
            <el-form-item label="手机号">
              <span v-text="scope.phonenum"></span>
            </el-form-item>
            <el-form-item label="所属校区">
              <span>{{ scope.schooladdressid?getschooladdress.find(v=> v.ID==scope.schooladdressid).name:'全部校区' }}</span>
            </el-form-item>
            <el-form-item label="角色">
              <span>{{ scope.schoolroleid?getschoolrole.find(v=>v.ID==scope.schoolroleid).name: '' }}</span>
            </el-form-item>
            <el-form-item label=" 上课教师">
              <span>{{scope.isteacher?'是':'否' }}</span>
            </el-form-item>
            <el-form-item label=" 上课范围">
              <span
                v-show="scope.isteacher"
              >{{scope.classscope === '*'?'全部校区':getschooladdress.filter(v=> scope.classscope.includes(v.ID)).map(v=> v.name).join(' ') }}</span>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="watchthis = false" type="primary" plain size="mini">返回</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  asynccreateschooluser,
  asyncchangeschooluser,
  asyncdelschooluser
} from "../../../../plugins/api.js";
export default {
  name: "user",
  data() {
    const isphone = (rule, value, callback) => {
      const reg = new RegExp(/^1[3456789]\d{9}$/);
      if (!reg.test(value)) {
        callback(new Error("手机格式不正确"));
      } else {
        callback();
      }
    };
    const ispassword = (rule, value, callback) => {
      const reg = new RegExp(/^[A-Za-z0-9]+$/);
      if (!reg.test(value)) {
        callback(new Error("密码只支持数字和字母"));
      } else {
        callback();
      }
    };
    return {
      mname: "",
      mphone: "",
      isaddress: true,
      setaddress: false,
      search: "",
      currentPage: 1,
      pagesize: 10,
      title: "添加员工",
      checkList: [],
      resource: true,
      ruleForm: {
        state: false,
        name: "",
        schoolroleid: "",
        phonenum: "",
        password: "",
        isteacher: false,
        sex: "",
        classscope: "",
        schooladdressid: 0
      },
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        password: [
          {
            min: 6,
            max: 30,
            message: "长度在 6 到 30 个字符",
            trigger: "blur"
          },
          { required: true, validator: ispassword, trigger: "blur" }
        ],
        phonenum: [{ required: true, validator: isphone, trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        classscope: [
          { required: true, validator: this.isclassscope, trigger: "blur" }
        ],
        schoolroleid: [
          { required: true, message: "请选择角色", trigger: "change" }
        ]
      },
      watchthis: false,
      index: 0
    };
  },
  computed: {
    ...mapGetters(["getschooluser", "getschooladdress", "getschoolrole", "getschoolrolebyid", ""]),
    tableData() {
      const { getschooluser, search, mname, mphone } = this;
      return getschooluser.filter(data => {
        const x = search ? data.schooladdressid == search : true;
        const y = mname ? data.name.includes(mname) : true;
        const z = mphone ? data.phonenum.toString().includes(mphone) : true;
        return x && y && z;
      });
    },
    scope() {
      return this.getschooluser.find(v => v.ID === this.index) || {};
    }
  },
  mounted() {
    if (this.getschooladdress.length) {
      this.isaddress = false;
    }
  },
  methods: {
    currentChange(index) {
      this.currentPage = index;
    },
    add(v) {
      this.setaddress = true;
      if (v) {
        this.title = "修改员工";
        const {
          ID,
          state,
          password,
          isteacher,
          schoolroleid,
          classscope,
          schooladdressid
        } = JSON.parse(JSON.stringify(v));
        if (classscope === "*") {
          this.resource = true;
        } else if (classscope === "") {
          this.resource = false;
          this.checkList = [];
        } else {
          this.resource = false;
          this.checkList = classscope.split(",").map(v => Number(v));
        }

        this.ruleForm = {
          ID,
          state,
          password,
          isteacher,
          schoolroleid,
          classscope,
          schooladdressid: schooladdressid ? schooladdressid : 0
        };
      } else {
        this.title = "添加员工";
        this.resource == true;
        this.checkList = [];
        this.ruleForm = {
          state: false,
          name: "",
          info: "",
          schoolroleid: "",
          phonenum: "",
          password: "",
          isteacher: false,
          schooladdressid: 0
        };
      }
    },
    del(ID) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger"
      })
        .then(async () => {
          try {
            await asyncdelschooluser({ ID });
            await this.$store.dispatch("actionschooluser");

            this.$message.success("删除成功");
          } catch (err) {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async state(row) {
      const data = JSON.parse(JSON.stringify(row));
      const x = data.state ? " 启用" : " 停用";
      this.$confirm(`是否${x}${row.name}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          data.state = !data.state;
          try {
            await asyncchangeschooluser(data);
            await this.$store.dispatch("actionschooluser");
            this.$message.success("已" + x);
          } catch (err) {
            this.$message.error(`操作失败：${err}`);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    async submitForm() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (this.$store.state.state) return;
          this.$store.commit("setstate", true);
          const data = this.ruleForm.ID ? "修改" : " 添加";
          if (this.resource) {
            this.ruleForm.classscope = "*";
          } else {
            this.ruleForm.classscope = this.checkList.join(",");
          }
          try {
            if (data === " 添加") {
              await asynccreateschooluser(this.ruleForm);
            } else {
              await asyncchangeschooluser(this.ruleForm);
            }
            await this.$store.dispatch("actionschooluser");
            this.setaddress = false;
            this.$message.success(`${data}成功`);
            this.ruleForm = {
              state: false,
              name: "",
              schoolroleid: "",
              phonenum: "",
              password: "",
              isteacher: false,
              sex: "",
              classscope: "",
              schooladdressid: 0
            };
          } catch (err) {
            this.$message.error(`${data}失败:${err}`);
          }
          this.$store.commit("setstate", false);
        } else {
          console.log("error submit!!");

          return false;
        }
      });
    },
    isclassscope(_rule, _value, callback) {
      if (this.ruleForm.isteacher) {
        if (!this.resource) {
          if (this.checkList.length === 0) {
            callback(new Error("选择了指定校区最少选择一个校区"));
            return;
          }
        }
      }
      callback();
    }
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.checkbox-group {
  padding-left: 30px;
  padding-right: 30px;
  padding-top: 15px;
  padding-bottom: 15px;
  background-color: #ededed;
}
</style>